﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using Ricciolo.Controls;
using OpenExpressApp.WPF.Controls;
using OpenExpressApp.Module.WPF.Editors.TreeColumn;
using OpenExpressApp.Module.WPF;
using System.Windows;
using System.Reflection;

namespace OpenExpressApp.WPF.Controls
{
    public static class ObjectTreeViewExtensionMethods
    {
        public static void UpdateContentTemplate(this TreeListViewItem lvi, bool isEditing)
        {
            // get the row presenter which holds all the column visuals per item
            GridViewRowPresenter rowPresenter = lvi.GetVisualChild<GridViewRowPresenter>();

            //新增树节点时还未显示界面时，需要手动调用一下ApplyTemplate
            if (null == rowPresenter)
            {
                lvi.ApplyTemplate();
                rowPresenter = lvi.GetVisualChild<GridViewRowPresenter>();
                rowPresenter.Columns = lvi.GetLogicalParent<TreeListView>().Columns;
                rowPresenter.ApplyTemplate();
            }

            // go through each column and update the content template
            int columnIndex = 0;
            foreach (GridViewColumn column in rowPresenter.Columns)
            {
                // get the content presenter of the particular column
                ContentPresenter cp = rowPresenter.GetVisualChild<ContentPresenter>(
                    (int)column.GetType().GetProperty("ActualIndex", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(column, null));

                TreeColumn treeColumn = column.GetValue(WPFMeta.TreeColumnProperty) as TreeColumn;
                if (null == treeColumn) continue;

                //树显示多个对象时，需要切换TreeColumn的PropertyInfo
                BusinessObjectPropertyInfo propInfo = ApplicationModel.GetBusinessObjectInfo(lvi.DataContext.GetType()).BOInfoByName(treeColumn.PropertyInfo.Name);
                if (null != propInfo)
                {
                    treeColumn.PropertyInfo = propInfo;
                    cp.ContentTemplate = null;
                    if (isEditing)
                    {
                        cp.Content = treeColumn.GenerateEditingFrameworkElement();
                    }
                    else
                    {
                        cp.Content = treeColumn.GenerateFrameworkElement();
                    }
                }
                //如果当前对象不存在列，则不生成控件
                else
                {
                    cp.ContentTemplate = null;
                    cp.Content = null;
                }

                columnIndex++;
            }
        }
    }
}
